package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qhzw.vip.qiyu.entity.DtsChargingPile;
import net.qhzw.vip.qiyu.mapper.DtsChargingPileMapper;
import net.qhzw.vip.qiyu.service.DtsChargingPileService;
import net.qhzw.vip.qiyu.util.CaculateDistance;
import net.qhzw.vip.qiyu.util.MyMathUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class DtsChargingPileServiceImpl extends ServiceImpl<DtsChargingPileMapper, DtsChargingPile> implements DtsChargingPileService {

    @Override
    public Page<DtsChargingPile> findList(Page<DtsChargingPile> page, String keywords, Double longitude, Double latitude) {
        Page<DtsChargingPile> pilePage = page(page, new LambdaQueryWrapper<DtsChargingPile>()
                .and(!StringUtils.isEmpty(keywords),
                        wq -> wq.like(DtsChargingPile::getName, keywords)
                                .or()
                                .like(DtsChargingPile::getAddress, keywords)).last("ORDER BY created DESC"));
        List<DtsChargingPile> list = pilePage.getRecords();
//        List<DtsChargingPile> list = list(new LambdaQueryWrapper<DtsChargingPile>()
//                .and(!StringUtils.isEmpty(keywords),
//                        wq -> wq.like(DtsChargingPile::getName, keywords)
//                                .or()
//                                .like(DtsChargingPile::getAddress, keywords)).last("ORDER BY created DESC"));
        if (!CollectionUtils.isEmpty(list) && longitude != null && latitude != null) {
            Collections.sort(list, new Comparator<DtsChargingPile>() {
                @Override
                public int compare(DtsChargingPile o1, DtsChargingPile o2) {
                    double distance1 = CaculateDistance.LantitudeLongitudeDist(longitude, latitude, o1.getLongitude(), o1.getLatitude());
                    double distance2 = CaculateDistance.LantitudeLongitudeDist(longitude, latitude, o2.getLongitude(), o2.getLatitude());
                    double d = distance1 - distance2;
                    return (int) d;
                }
            });
            list.forEach(data -> data.setDistance(MyMathUtil.dFormat(CaculateDistance.LantitudeLongitudeDist(longitude, latitude, data.getLongitude(),
                    data.getLatitude()) / 1000)));
        }
        return pilePage;
    }
}
